import router from "@/router";
import store from "@/store";
import ACCESS_ENUMS from "@/access/accessEnums";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  const loginUser = store.state.user.loginUser;
  if (!loginUser || loginUser.userRole === ACCESS_ENUMS.NOT_LOGIN) {
    await store.dispatch("user/getLoginUser");
  }
  const needAccess = (to.meta?.access as string) ?? ACCESS_ENUMS.NOT_LOGIN;
  if (needAccess !== ACCESS_ENUMS.NOT_LOGIN) {
    if (!loginUser) {
      next(`user/login?redirect=${to.fullPath}`);
      return;
    }
    if (!checkAccess(loginUser, needAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
